<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>动态创建DOM节点练习</title>
  </head>
  <body>
    <form id="form">
      <p>姓名: <input type="checkbox" value="姓名" /></p>
      <p>年龄: <input type="checkbox" value="年龄" /></p>
      <p>性别: <input type="checkbox" value="性别" /></p>
      <input type="button" value="添加文本框" onclick="addTextField()" />
    </form>
    <script>
      function addTextField() {
        let list = document.querySelector("#list");
        if (list === null) {
          list = document.createElement("ul");
          list.id = "list";
          list.style.listStyleType = "none";
          const form = document.querySelector("#form");
          for (let elm of form.children) {
            if (elm.children[0] === undefined) break;
            if (elm.children[0].checked) {
              const nw = document.createElement("li");
              nw.textContent = elm.children[0].value + ": ";
              nw.append(document.createElement("input"));
              list.append(nw);
            }
          }
          form.append(list);
        } else {
          list.remove();
        }
      }
    </script>
  </body>
</html>
